package com.atguigu.day03;

import com.alibaba.fastjson.JSON;
import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.redis.RedisSink;
import org.apache.flink.streaming.connectors.redis.common.config.FlinkJedisPoolConfig;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommand;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommandDescription;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisMapper;

public class Flink12_Sink_Redis {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.从端口读取数据并转为JavaBean
        SingleOutputStreamOperator<WaterSensor> result = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                });
        //TODO 3.将数据写入Redis
        result.addSink(new RedisSink<>(
                new FlinkJedisPoolConfig.Builder()
                        .setHost("hadoop102")
                        .setPort(6379)
                        .build(),
                new RedisMapper<WaterSensor>() {
                    //用来指定写的命令 从而决定用什么数据结构存储
                    @Override
                    public RedisCommandDescription getCommandDescription() {
                        return new RedisCommandDescription(RedisCommand.SET);
                    }

                    //默认情况下 从数据中获取key 指定为RedisKey
                    @Override
                    public String getKeyFromData(WaterSensor data) {
                        return data.getId();
                    }

                    //默认情况下 从数据中获取要存到Redis的Value
                    @Override
                    public String getValueFromData(WaterSensor data) {
                        //将数据转为Json字符串存入Redisd 这么做是为了方便后续取出来好解析
                        String jsonString = JSON.toJSONString(data);
                        return jsonString;
                    }
                }
        ));

        env.execute();
    }
}
